﻿using Microsoft.AspNetCore.Mvc;
using YDT_PaymentService.Applictions.DTOs;
using YDT_PaymentService.Applictions.Interfaces;

namespace YDT_PaymentService.Api.Controllers
{
    /// <summary>
    /// 支付控制器 - 处理支付相关的HTTP请求
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class PaymentsController : ControllerBase
    {
        private readonly IPaymentService _paymentService;

        /// <summary>
        /// 构造函数 - 依赖注入支付服务
        /// </summary>
        public PaymentsController(IPaymentService paymentService)
        {
            _paymentService = paymentService;
        }

        /// <summary>
        /// 获取所有支付记录
        /// </summary>
        /// <returns>支付记录列表</returns>
        [HttpGet]
        public async Task<ActionResult<IEnumerable<PaymentDto>>> GetPayments()
        {
            var payments = await _paymentService.GetAllPaymentsAsync();
            return Ok(payments);
        }

        /// <summary>
        /// 根据ID获取支付记录
        /// </summary>
        /// <param name="id">支付记录ID</param>
        /// <returns>支付记录信息</returns>
        [HttpGet("{id:guid}")]
        public async Task<ActionResult<PaymentDto>> GetPayment(Guid id)
        {
            var payment = await _paymentService.GetPaymentByIdAsync(id);
            if (payment == null)
            {
                return NotFound($"支付记录ID '{id}' 不存在");
            }
            return Ok(payment);
        }

        /// <summary>
        /// 根据支付单号获取支付记录
        /// </summary>
        /// <param name="paymentCode">支付单号</param>
        /// <returns>支付记录信息</returns>
        [HttpGet("code/{paymentCode}")]
        public async Task<ActionResult<PaymentDto>> GetPaymentByCode(string paymentCode)
        {
            var payment = await _paymentService.GetPaymentByCodeAsync(paymentCode);
            if (payment == null)
            {
                return NotFound($"支付单号 '{paymentCode}' 不存在");
            }
            return Ok(payment);
        }

        /// <summary>
        /// 根据订单ID获取支付记录
        /// </summary>
        /// <param name="orderId">订单ID</param>
        /// <returns>支付记录信息</returns>
        [HttpGet("order/{orderId:guid}")]
        public async Task<ActionResult<PaymentDto>> GetPaymentByOrderId(Guid orderId)
        {
            var payment = await _paymentService.GetPaymentByOrderIdAsync(orderId);
            if (payment == null)
            {
                return NotFound($"订单ID '{orderId}' 的支付记录不存在");
            }
            return Ok(payment);
        }

        /// <summary>
        /// 获取用户的所有支付记录
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>支付记录列表</returns>
        [HttpGet("user/{userId:guid}")]
        public async Task<ActionResult<IEnumerable<PaymentDto>>> GetPaymentsByUser(Guid userId)
        {
            var payments = await _paymentService.GetPaymentsByUserIdAsync(userId);
            return Ok(payments);
        }

        /// <summary>
        /// 分页查询支付记录
        /// </summary>
        /// <param name="query">查询参数</param>
        /// <returns>分页支付记录列表</returns>
        [HttpGet("paged")]
        public async Task<ActionResult> GetPagedPayments([FromQuery] PaymentQueryDto query)
        {
            var (payments, totalCount) = await _paymentService.GetPagedPaymentsAsync(query);
            return Ok(new { Payments = payments, TotalCount = totalCount });
        }

        /// <summary>
        /// 创建支付记录
        /// </summary>
        /// <param name="createPaymentDto">创建支付记录参数</param>
        /// <returns>创建的支付记录信息</returns>
        [HttpPost]
        public async Task<ActionResult<PaymentDto>> CreatePayment(CreatePaymentDto createPaymentDto)
        {
            try
            {
                var payment = await _paymentService.CreatePaymentAsync(createPaymentDto);
                return CreatedAtAction(nameof(GetPayment), new { id = payment.Id }, payment);
            }
            catch (InvalidOperationException ex)
            {
                return BadRequest(ex.Message);
            }
            catch (ArgumentException ex)
            {
                return BadRequest(ex.Message);
            }
        }

        /// <summary>
        /// 更新支付记录
        /// </summary>
        /// <param name="id">支付记录ID</param>
        /// <param name="updatePaymentDto">更新支付记录参数</param>
        /// <returns>更新后的支付记录信息</returns>
        [HttpPut("{id:guid}")]
        public async Task<ActionResult<PaymentDto>> UpdatePayment(Guid id, UpdatePaymentDto updatePaymentDto)
        {
            var payment = await _paymentService.UpdatePaymentAsync(id, updatePaymentDto);
            if (payment == null)
            {
                return NotFound($"支付记录ID '{id}' 不存在");
            }
            return Ok(payment);
        }

        /// <summary>
        /// 删除支付记录
        /// </summary>
        /// <param name="id">支付记录ID</param>
        /// <returns>删除结果</returns>
        [HttpDelete("{id:guid}")]
        public async Task<ActionResult> DeletePayment(Guid id)
        {
            try
            {
                var result = await _paymentService.DeletePaymentAsync(id);
                if (!result)
                {
                    return NotFound($"支付记录ID '{id}' 不存在");
                }
                return NoContent();
            }
            catch (InvalidOperationException ex)
            {
                return BadRequest(ex.Message);
            }
        }

        /// <summary>
        /// 初始化支付
        /// </summary>
        /// <param name="id">支付记录ID</param>
        /// <param name="initializeDto">初始化支付参数</param>
        /// <returns>初始化后的支付记录信息</returns>
        [HttpPost("{id:guid}/initialize")]
        public async Task<ActionResult<PaymentDto>> InitializePayment(Guid id, InitializePaymentDto initializeDto)
        {
            var payment = await _paymentService.InitializePaymentAsync(id, initializeDto);
            if (payment == null)
            {
                return NotFound($"支付记录ID '{id}' 不存在");
            }
            return Ok(payment);
        }

        /// <summary>
        /// 处理支付成功（支付平台回调）
        /// </summary>
        /// <param name="paymentCode">支付单号</param>
        /// <returns>处理结果</returns>
        [HttpPost("success/{paymentCode}")]
        public async Task<ActionResult<PaymentDto>> ProcessPaymentSuccess(string paymentCode)
        {
            var payment = await _paymentService.ProcessPaymentSuccessAsync(paymentCode);
            if (payment == null)
            {
                return NotFound($"支付单号 '{paymentCode}' 不存在");
            }
            return Ok(payment);
        }

        /// <summary>
        /// 处理支付失败（支付平台回调）
        /// </summary>
        /// <param name="paymentCode">支付单号</param>
        /// <param name="errorNo">错误编号</param>
        /// <param name="errorInfo">错误信息</param>
        /// <returns>处理结果</returns>
        [HttpPost("failure/{paymentCode}")]
        public async Task<ActionResult<PaymentDto>> ProcessPaymentFailure(string paymentCode,
            [FromQuery] string errorNo, [FromQuery] string errorInfo)
        {
            var payment = await _paymentService.ProcessPaymentFailureAsync(paymentCode, errorNo, errorInfo);
            if (payment == null)
            {
                return NotFound($"支付单号 '{paymentCode}' 不存在");
            }
            return Ok(payment);
        }

        /// <summary>
        /// 取消支付
        /// </summary>
        /// <param name="id">支付记录ID</param>
        /// <returns>取消后的支付记录信息</returns>
        [HttpPost("{id:guid}/cancel")]
        public async Task<ActionResult<PaymentDto>> CancelPayment(Guid id)
        {
            var payment = await _paymentService.CancelPaymentAsync(id);
            if (payment == null)
            {
                return NotFound($"支付记录ID '{id}' 不存在");
            }
            return Ok(payment);
        }

        /// <summary>
        /// 开始退款流程
        /// </summary>
        /// <param name="id">支付记录ID</param>
        /// <returns>开始退款后的支付记录信息</returns>
        [HttpPost("{id:guid}/refund/start")]
        public async Task<ActionResult<PaymentDto>> StartRefund(Guid id)
        {
            var payment = await _paymentService.StartRefundAsync(id);
            if (payment == null)
            {
                return NotFound($"支付记录ID '{id}' 不存在");
            }
            return Ok(payment);
        }

        /// <summary>
        /// 处理退款成功
        /// </summary>
        /// <param name="id">支付记录ID</param>
        /// <returns>退款成功后的支付记录信息</returns>
        [HttpPost("{id:guid}/refund/success")]
        public async Task<ActionResult<PaymentDto>> ProcessRefundSuccess(Guid id)
        {
            var payment = await _paymentService.ProcessRefundSuccessAsync(id);
            if (payment == null)
            {
                return NotFound($"支付记录ID '{id}' 不存在");
            }
            return Ok(payment);
        }

        /// <summary>
        /// 处理退款失败
        /// </summary>
        /// <param name="id">支付记录ID</param>
        /// <param name="errorNo">错误编号</param>
        /// <param name="errorInfo">错误信息</param>
        /// <returns>退款失败后的支付记录信息</returns>
        [HttpPost("{id:guid}/refund/failure")]
        public async Task<ActionResult<PaymentDto>> ProcessRefundFailure(Guid id,
            [FromQuery] string errorNo, [FromQuery] string errorInfo)
        {
            var payment = await _paymentService.ProcessRefundFailureAsync(id, errorNo, errorInfo);
            if (payment == null)
            {
                return NotFound($"支付记录ID '{id}' 不存在");
            }
            return Ok(payment);
        }
    }
}
